﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TaiwuModFramework.Common.Abstract;

namespace TaiwuModFramework.Common.Base {
    public class BaseLogger : ALogger {

        public bool KeepHeader { get; set; } = true;

        public BaseLogger(string name, LEVEL level, ALogWriter logWriter) {
            Name = name;
            Level = level;
            LogWriter = logWriter;
        }
        public BaseLogger(string name, LEVEL level) : this(name, level, null) {

        }
        public BaseLogger(string name) : this(name, LEVEL.INFO, null) { }

        protected override void WriteToLogPath(LEVEL level, string msg) {
            if(msg == null) return;
            if(LogWriter == null && level < LEVEL.WARN) return;

            string timeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff");
            string lineIndexStr = "|0000";
            //string otherInfo = string.Format("|{0,-5}|{1}|{2}|", level, Thread.CurrentThread.Name, Name);
            string otherInfo = string.Format("|{0,-5}|{1}|", level, Name);

            var sb = new StringBuilder(30 + 30 + msg.Length);
            if(KeepHeader) {
                string[] lines = msg.Split('\n');
                for(int i = 0; i < lines.Length; i++) {
                    lineIndexStr = string.Format("{0:0000}|", i);
                    sb.Append(timeStr).Append(otherInfo).Append(lineIndexStr);
                    sb.Append(lines[i]);
                    if(i < lines.Length - 1) {
                        sb.Append('\n');
                    }
                }
            } else {
                sb.Append(timeStr).Append(lineIndexStr).Append(otherInfo);
                sb.Append(msg);
            }
            if(LogWriter != null) {
                LogWriter.WriteLine(sb.ToString());
            }
        }
    }
}
